package cn.school.servlet.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * @author oldliu
 * @since 1.0
 */
@WebFilter(value = "/*", filterName = "roleFilter")
public class RoleFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了RoleFilter，时间是:"+new Date());
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String path = request.getServletPath();
        if (path.equals("/login.jsp") || path.equals("/loginServlet") || path.endsWith(".css") || path.endsWith(".js") || path.endsWith(".jpg") || path.endsWith(".png")|| path.endsWith(".html")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        if (request.getSession().getAttribute("USER_LOGIN") == null) {
            request.setAttribute("msg", "您还没有登录，请登录");
            request.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);

        System.out.println("离开了RoleFilter，时间是:"+new Date());
    }

    @Override
    public void destroy() {

    }
}
